package com.zhuangzhuang.dahua.component;

import com.netsdk.demo.module.AutoRegisterModule;
import com.netsdk.demo.module.LoginModule;
import com.netsdk.lib.NetSDKLib;
import com.sun.jna.Pointer;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

@Component
public class AutoRegisterRunner  implements CommandLineRunner {
    // 设备链接回调
    // 主动注册监听回调
    private ServiceCB serviceCallback = new ServiceCB();


    @Override
    public void run(String... args) throws Exception {
        System.out.println("AutoRegisterRunner 执行了");

        LoginModule.init(null, null);
        boolean result = AutoRegisterModule.startServer("192.168.1.9", 9500,serviceCallback);
//        if (result) {
//            System.out.println("Server started successfully.");
//        } else {
//            System.err.println("Failed to start server.");
//        }
    }


    /**
     * 设备下线回调
     */
    private class DisConnect implements NetSDKLib.fDisConnect {
        @Override
        public void invoke(NetSDKLib.LLong lLoginID, String pchDVRIP, int nDVRPort, Pointer dwUser) {
            System.out.printf("Device[%s] Port[%d] DisConnect!\n", pchDVRIP, nDVRPort);
        }
    }


    /**
     * 设备链接回调
     */
    public class ServiceCB implements NetSDKLib.fServiceCallBack {
        @Override
        public int invoke(NetSDKLib.LLong lHandle, String pIp, int wPort, int lCommand, Pointer pParam, int dwParamLen, Pointer dwUserData) {
            // 将 pParam 转化为序列号
            byte[] buffer = new byte[dwParamLen];
            pParam.read(0, buffer, 0, dwParamLen);
            String deviceId = "";
            try {
                deviceId = new String(buffer, "GBK").trim();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            System.out.println("设备序列号：" + deviceId);

            return 0;
        }

    }
}
